package com.server.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.server.common.QueryPageParam;
import com.server.common.Result;
import com.server.entity.Manager;
import com.server.entity.User;
import com.server.service.ManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;



@CrossOrigin
@RestController
@RequestMapping("/manager")
public class ManagerController {

	@Autowired
	private ManagerService managerService;

	@PostMapping("/login")
	public Result login(@RequestBody Map map) {
		List<Manager> list=managerService.lambdaQuery()
				.eq(Manager::getId,map.get("id"))
				.eq(Manager::getPassword, map.get("password")).list();
		return !list.isEmpty() ?Result.suc(list.get(0),1L):Result.fail();
	}

	@PostMapping("/saveORmodify")
	public Result saveORmodify(@RequestBody Manager manager){
		System.out.println(manager);
		if(!manager.isIdNull()&&manager.getId()==1)
			manager.setIssuper(true);
		if(managerService.saveOrUpdate(manager))
			return Result.suc(null, 1L);
		else
			return Result.fail();
	}
	@PostMapping("/delete")
	public Result delete(@RequestBody Map<String, List<Integer>> requestMap){
		boolean res = true;
		List<Integer> ids = requestMap.get("ids");
		for(Integer id : ids){
			if(id==1)
				continue;
			if(id!=null)
				res=res&managerService.removeById(id);
		}
		if(res)
			return Result.suc(null, 1L);
		else
			return Result.fail();
	}

	@PostMapping("/querylike")
	public Result querylike(@RequestBody QueryPageParam query) {
		// 创建分页对象
		Page<Manager> page = new Page<>(query.getPageNum(), query.getPageSize());
		// 获取查询参数
		HashMap<String, Object> map = query.getParam();
		// 创建条件构造器
		LambdaQueryWrapper<Manager> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		// 动态拼接条件
		String name = map.get("name") != null ? map.get("name").toString().trim() : "";
		String email = map.get("email") != null ? map.get("email").toString().trim() : "";
		String id = map.get("id") != null ? map.get("id").toString().trim() : "";
		if (!name.isEmpty()) {
			lambdaQueryWrapper.like(Manager::getName, name);
		}
		if (!email.isEmpty()) {
			lambdaQueryWrapper.like(Manager::getEmail, email);
		}
		if (!id.isEmpty()) {
			lambdaQueryWrapper.eq(Manager::getId, id); // 精确查询
		}
		// 执行查询
		IPage<Manager> res = managerService.pageC(page, lambdaQueryWrapper);
		// 返回结果
		return Result.suc(res.getRecords(), res.getTotal());
	}
}
